package com.binyong.websocket;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * websocket
 */
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId="";


    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
        }
        log.info("websoket 用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("connectSuccess");
        } catch (IOException e) {
            log.error("websoket 用户:"+userId+",连接异常"+e.getMessage());
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @SuppressWarnings("unchecked")
	@OnClose
    public void onClose() {
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
        }
        log.info("websoket 用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info(String.format("WebSocketCustomServer[%s]收到消息："+message,userId));
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websoket 用户错误:"+this.userId+",原因:"+error.getMessage());
    }
    /**
     * 实现服务器主动推送
     */
    public synchronized void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
    }


    /**
     * 给指定客户发送消息
     * */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
        if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
            log.info("websoket 发送消息到客户:"+userId+"，报文:"+message);
            webSocketMap.get(userId).sendMessage(message);
        }
    }

    /**
     * 对所有客户发送消息
     * @param message
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
	public static void sendInfoAll(String message) throws IOException {
    	Set<String> set = webSocketMap.keySet();
    	for(String userId : set) {
    		log.info("websoket 发送消息到客户:"+userId+"，报文:"+message);
            webSocketMap.get(userId).sendMessage(message);
    	}
    }
    public static int getOnlineCount() {
        return webSocketMap.size();
    }
}
